<template>
  <div class="tree-node">
    <el-icon v-if="data.type === 'folder'" class="folder-icon">
      <FolderOpened v-if="node.expanded" />
      <Folder v-else />
    </el-icon>
    <el-icon v-else class="document-icon">
      <component :is="getFileIcon(data)" />
    </el-icon>

    <span v-if="!data.editing" class="node-label" @dblclick="onDblClick">
      {{ node.label }}
    </span>

    <el-input
      v-else
      ref="renameInput"
      v-model="data.label"
      size="small"
      @blur="finishRename"
      @keyup.enter="finishRename"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { FolderOpened, Folder } from '@element-plus/icons-vue'
import { getFileIcon } from '@/utils/document'

const props = defineProps({
  node: Object,
  data: Object
})

const emit = defineEmits(['rename', 'finish-rename'])

const renameInput = ref(null)

const onDblClick = () => {
  if (props.data.type === 'folder') return
  emit('rename')
}

const finishRename = () => {
  emit('finish-rename')
}

onMounted(() => {
  if (props.data.editing && renameInput.value) {
    renameInput.value.focus()
  }
})
</script>

<style scoped>
.tree-node {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 5px 0;
}

.tree-node .el-icon {
  margin-right: 8px;
  font-size: 18px;
}

.tree-node .folder-icon {
  color: #e6a23c;
}

.tree-node .document-icon {
  color: #409eff;
}

.node-label {
  flex: 1;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: default;
}
</style>